import 'dart:async';
import 'package:amap_flutter_base/amap_flutter_base.dart' show LatLng;
import 'package:amap_flutter_map/amap_flutter_map.dart';
import 'package:amap_search_fluttify/amap_search_fluttify.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:flutter/material.dart';
import 'package:gourmet/color/hex.dart';
import 'package:gourmet/config/amap_config.dart';
import 'package:gourmet/event/index.dart';
import 'package:gourmet/extensions/ex_widget.dart';
import 'package:gourmet/extensions/fun.dart';
import 'package:gourmet/route/index.dart';
import 'package:gourmet/utils/colors.dart';
import 'package:gourmet/utils/styles.dart';
import 'package:sliding_up_panel/sliding_up_panel.dart';

class ReceiveAddressMapController extends GetxController {
  late AMapController controller;

  RxList<Poi> searchs = RxList([]);

  StreamSubscription<LocationEvent>? locationSubscription;

  // late Uint8List byteData;

  Rx<Uint8List>? byteData;

  /// 地图上显示的Marker
  Rx<Set<Marker>> markers = Rx({});

  Rx<LatLng> latLng = Rx(const LatLng(21.481305, 109.120248));

  String city = '北海市';

  RxString street = RxString('北海市北站中心公园');

  RxString address = RxString('北海市海城区西南大道4896号');

  @override
  void onInit() {
    _initPngIcon();
    locationSubscription = eventBus.on<LocationEvent>().listen((event) {
      latLng.value = LatLng(event.result['latitude'] as double,
          event.result['longitude'] as double);
      city = event.result['city'] as String;
      searchs.clear();
      markers.value.clear();
    });
    super.onInit();
  }

  @override
  void onClose() {
    locationSubscription?.cancel();
    super.onClose();
  }

  void onMapCreated(AMapController controller) {
    this.controller = controller;
  }

  void searchAddress(String keyword) {
    AmapSearch.instance
        .searchKeyword(keyword, city: city)
        .then((List<Poi> result) {
      searchs.clear();
      markers.value.clear();
      for (var r in result) {
        searchs.add(r);
        if (r.latLng != null) {
          markers.value.add(
            Marker(
              position: LatLng(r.latLng!.latitude, r.latLng!.longitude),
              infoWindow: InfoWindow(title: r.title!, snippet: r.address!),
            ),
          );
        }
      }
    });
  }

  void _initPngIcon() async {
    final ByteData bytes = await rootBundle.load('assets/image/u9089.png');
    byteData = Rx(bytes.buffer.asUint8List());
  }
}

class ReceiveAddressMapPage extends GetView<ReceiveAddressMapController> {
  const ReceiveAddressMapPage({super.key});

  Widget _scrollingList(ScrollController sc) {
    return Obx(
      () => ListView(
        controller: sc,
        children: [
          Container(
            padding: const EdgeInsets.only(top: 20, left: 20),
            child: Column(
              children: [
                Container(
                  alignment: Alignment.centerLeft,
                  child: Text.rich(
                    TextSpan(
                      children: [
                        WidgetSpan(
                            child: Icon(
                              CupertinoIcons.placemark_fill,
                              size: 18,
                              color: HexColor(ColorsUtils.colorFf6e),
                            ),
                            alignment: PlaceholderAlignment.middle),
                        TextSpan(
                          text: ' ${controller.street}',
                          style: StylesUtils.customTextStyle(
                              fontSize: StylesUtils.fontSize15,
                              color: ColorsUtils.colorFf64),
                        ),
                      ],
                    ),
                  ),
                ),
                Container(
                  margin: const EdgeInsets.only(top: 10),
                  alignment: Alignment.centerLeft,
                  child: Text(
                    '${controller.address}',
                    style: StylesUtils.customTextStyle(
                      color: ColorsUtils.color9999,
                      fontSize: StylesUtils.fontSize13,
                    ),
                  ),
                ),
                Divider(
                  height: 30,
                  indent: 0,
                  endIndent: 0,
                  color: HexColor(ColorsUtils.colorF5f5),
                  thickness: 1,
                ),
              ],
            ),
          ),
          ...controller.searchs.map(
            (s) => Container(
              padding: const EdgeInsets.only(left: 20),
              child: Column(
                children: [
                  Container(
                    alignment: Alignment.centerLeft,
                    child: Text.rich(
                      TextSpan(
                        children: [
                          TextSpan(
                            text: '${s.title}',
                            style: StylesUtils.customTextStyle(
                                fontSize: StylesUtils.fontSize15,
                                color: ColorsUtils.color0000),
                          ),
                        ],
                      ),
                    ),
                  ),
                  Container(
                    margin: const EdgeInsets.only(top: 10),
                    alignment: Alignment.centerLeft,
                    child: Text(
                      s.address ?? '',
                      style: StylesUtils.customTextStyle(
                        color: ColorsUtils.color9999,
                        fontSize: StylesUtils.fontSize13,
                      ),
                    ),
                  ),
                  Divider(
                    height: 30,
                    indent: 0,
                    endIndent: 0,
                    color: HexColor(ColorsUtils.colorF5f5),
                    thickness: 1,
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.white,
        systemOverlayStyle: SystemUiOverlayStyle.dark,
        leading: IconButton(
          onPressed: Get.back,
          icon: Icon(
            CupertinoIcons.chevron_back,
            size: 20.sp,
            color: HexColor(ColorsUtils.color0000),
          ),
        ),
        title: Text(
          '地址搜索',
          style: StylesUtils.customTextStyle(
            fontSize: StylesUtils.fontSize16,
            color: ColorsUtils.color0000,
            fontWeight: FontWeight.w700,
          ),
        ),
        centerTitle: true,
        actions: [
          TextButton(
            onPressed: () {},
            child: Text(
              '取消',
              style: StylesUtils.customTextStyle(
                fontSize: StylesUtils.fontSize15,
                color: ColorsUtils.color0000,
              ),
            ),
          ),
        ],
      ),
      body: Stack(
        children: [
          Obx(
            () => AMapWidget(
              privacyStatement: AmapConfig.amapPrivacyStatement,
              apiKey: AmapConfig.amapApiKeys,
              onMapCreated: controller.onMapCreated,
              initialCameraPosition:
                  CameraPosition(target: controller.latLng.value, zoom: 14),
              myLocationStyleOptions: MyLocationStyleOptions(
                true,
                icon: controller.byteData != null
                    ? BitmapDescriptor.fromBytes(controller.byteData!.value)
                    : null,
              ),
              minMaxZoomPreference: const MinMaxZoomPreference(10, 19),
              markers: controller.markers.value,
            ),
          ),
          Positioned(
            top: 15,
            left: (Get.width - 345) / 2,
            width: 345,
            height: 40,
            child: TextField(
              cursorHeight: 20,
              cursorWidth: 3,
              cursorRadius: const Radius.circular(2),
              cursorColor: HexColor(ColorsUtils.colorFf64),
              style: StylesUtils.customTextStyle(
                fontSize: StylesUtils.fontSize15,
                color: ColorsUtils.color0000,
              ),
              textAlign: TextAlign.left,
              textAlignVertical: TextAlignVertical.center,
              textDirection: TextDirection.ltr,
              keyboardType: TextInputType.text,
              decoration: InputDecoration(
                hintText: '请输入地址',
                hintStyle: StylesUtils.customTextStyle(
                  fontSize: StylesUtils.fontSize15,
                  color: ColorsUtils.color9999,
                ),
                filled: true,
                fillColor: Colors.white,
                isDense: true,
                isCollapsed: true,
                prefixIconConstraints:
                    const BoxConstraints.expand(height: 50, width: 150),
                prefixIcon: Container(
                  alignment: Alignment.center,
                  child: Text.rich(
                    TextSpan(
                      children: [
                        WidgetSpan(
                            child: Icon(
                              CupertinoIcons.placemark_fill,
                              size: 20,
                              color: HexColor(ColorsUtils.colorFf64),
                            ),
                            alignment: PlaceholderAlignment.middle),
                        TextSpan(
                          text: ' 北海市 ',
                          style: StylesUtils.customTextStyle(
                            fontSize: StylesUtils.fontSize16,
                            color: ColorsUtils.color0000,
                          ),
                        ),
                        WidgetSpan(
                            child: Icon(
                              CupertinoIcons.arrowtriangle_down_fill,
                              color: HexColor(ColorsUtils.color9999),
                              size: 14,
                            ),
                            alignment: PlaceholderAlignment.middle),
                        TextSpan(
                          text: '  |  ',
                          style: StylesUtils.customTextStyle(
                            color: ColorsUtils.colorCccc,
                            fontSize: StylesUtils.fontSize17,
                          ),
                        ),
                        WidgetSpan(
                          child: Icon(
                            CupertinoIcons.search,
                            size: 20,
                            color: HexColor(ColorsUtils.color9999),
                          ),
                        ),
                      ],
                    ),
                  ),
                ).onTap(() {
                  Get.toNamed(Routes.mineReceiveAddressCity);
                }),
                contentPadding:
                    const EdgeInsets.symmetric(vertical: 10, horizontal: 20),
                enabledBorder: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(20),
                  borderSide: BorderSide.none,
                ),
                focusedBorder: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(20),
                  borderSide: BorderSide.none,
                ),
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(20),
                  borderSide: BorderSide.none,
                ),
                constraints:
                    const BoxConstraints.expand(width: 345, height: 40),
              ),
              onChanged: (String keyword) {}.useDebounce((String keyword) {
                controller.searchAddress(keyword);
              }),
            ),
          ),
          SlidingUpPanel(
            minHeight: 50,
            panelBuilder: (ScrollController sc) => _scrollingList(sc),
            onPanelOpened: () {
              Get.log('opened');
            },
            onPanelClosed: () {
              Get.log('closed');
            },
          )
        ],
      ),
    );
  }
}
